package com.android.msntop.services;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

public class PingNotifier extends Service{

	private int mStartId;
	public static String ACTION_CHECK = "com.android.msntop.intent.action.CHECK";
	public static String ACTION_CANCEL = "com.android.msntop.intent.action.CANCEL";
	public static String ACTION_RESCHEDULE = "com.android.msntop.intent.action.RESCHEDULE";

	public static void actionReschedule(Context context) {
        Intent i = new Intent();
        i.setClass(context, PingNotifier.class);
        i.setAction(PingNotifier.ACTION_RESCHEDULE);
        context.startService(i);
    }

    public static void actionCancel(Context context)  {
        Intent i = new Intent();
        i.setClass(context, PingNotifier.class);
        i.setAction(PingNotifier.ACTION_CANCEL);
        context.startService(i);
    }
	
	public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        this.mStartId = startId;


        if (ACTION_CHECK.equals(intent.getAction()))
        {
        	Log.i("PingNotifier", "Got ACTION_CHECK");
        	checkHosts();
        }
        else if (ACTION_CANCEL.equals(intent.getAction()))
        {
        	Log.i("PingNotifier", "Got ACTION_CANCEL");
        	cancel();
            stopSelf(startId);
        }
        else if(ACTION_RESCHEDULE.equals(intent.getAction()))
        {
        	reschedule();
            stopSelf(startId);
        }
	}
	
	private void reschedule() {
		AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
		Intent i = new Intent();
		i.setClassName("com.android.msntop", "com.android.msntop.services.PingNotifier");
		i.setAction(ACTION_CHECK);
		PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
		
		int interval = 1;
		
		alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()
                + (interval * (60 * 1000)), pi);
		
	}

	private void cancel() 
	{
		AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
		Intent i = new Intent();
		i.setClassName("com.android.msntop", "com.android.msntop.services.PingNotifier");
		i.setAction(ACTION_CHECK);
		PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
		alarmMgr.cancel(pi);
	}
	
	private void checkHosts() {
		// TODO Auto-generated method stub
		
	}

	public void foo()
	{
        AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
		int interval = 1; 
    	// TODO - Determine interval from preferences
        //PendingIntent pi = PendingIntent.getService(this, 0, i, 0);

	}
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	

}
